package utils

import (
	"fmt"
	"qcoder_reader/config"

	consulapi "github.com/hashicorp/consul/api"
)

var consulClient *consulapi.Client

func InitConsul() error {
	consulConfig := config.AppConfig.Consul

	cfg := &consulapi.Config{
		Address: fmt.Sprintf("%s:%d", consulConfig.Host, consulConfig.Port),
		Scheme:  consulConfig.Scheme,
	}

	client, err := consulapi.NewClient(cfg)
	if err != nil {
		return err
	}

	consulClient = client
	return nil
}

func GetConsulClient() *consulapi.Client {
	return consulClient
}

func GetAllServices() (map[string][]string, error) {
	catalog := consulClient.Catalog()
	services, _, err := catalog.Services(nil)
	return services, err
}

func GetServiceDetails(serviceName string) ([]*consulapi.CatalogService, error) {
	catalog := consulClient.Catalog()
	services, _, err := catalog.Service(serviceName, "", nil)
	return services, err
}

func RegisterService(service *consulapi.AgentServiceRegistration) error {
	return consulClient.Agent().ServiceRegister(service)
}

func DeregisterService(serviceID string) error {
	return consulClient.Agent().ServiceDeregister(serviceID)
}
